import { defineStore } from 'pinia';
import { ref } from 'vue';

// 应用级别的全局状态，避免页面切换时重置
let appLevelEventListenersInitialized = false;
let appLevelActiveComponents = 0;

// 存储事件处理函数引用，用于正确移除监听器
let eventHandlers: {
  start?: (e: any) => void;
  volumeChange?: (e: any) => void;
  recognizing?: (e: any) => void;
  recognition?: (e: any) => void;
  end?: (e: any) => void;
} = {};

// 事件去重机制
let lastRecognitionResult = '';
let lastRecognitionTime = 0;
let lastEndTime = 0;

export const useVoiceRecognitionStore = defineStore('voiceRecognition', () => {
  // 状态
  const isRecording = ref(false);
  const currentComponentId = ref<string | null>(null);
  const recognitionResult = ref('');
  const previewText = ref('');
  const waveformData = ref<number[]>([]);
  const showModal = ref(false);
  const isWaitingForFinalResult = ref(false);

  // 语音识别配置
  const speechOptions = {
    engine: 'baidu',
    lang: 'zh-cn',
    continue: true,
    userInterface: false,
    timeout: 10000
  };

  // 生成波形数据
  const generateWaveform = (volume = 0) => {
    const bars = [];
    const barCount = 40;
    const maxHeight = 100;
    
    for (let i = 0; i < barCount; i++) {
      const center = barCount / 2;
      const distance = Math.abs(i - center);
      
      let baseHeight;
      if (distance <= 1) {
        baseHeight = maxHeight;
      } else if (distance <= 3) {
        baseHeight = maxHeight - (distance - 1) * 5;
      } else if (distance <= 6) {
        baseHeight = maxHeight - 10 - (distance - 3) * 6;
      } else if (distance <= 10) {
        baseHeight = maxHeight - 28 - (distance - 6) * 4;
      } else if (distance <= 15) {
        baseHeight = maxHeight - 44 - (distance - 10) * 3;
      } else {
        baseHeight = Math.max(10, maxHeight - 100);
      }
      
      const volumeFactor = Math.max(0.1, volume);
      const height = Math.max(8, baseHeight * volumeFactor + Math.random() * 15);
      
      bars.push(height);
    }
    waveformData.value = bars;
  };

  // 移除所有事件监听器
  const removeAllEventListeners = () => {
    
    try {
      if (eventHandlers.start) {
        plus.speech.removeEventListener('start', eventHandlers.start, false);
      }
      if (eventHandlers.volumeChange) {
        plus.speech.removeEventListener('volumeChange', eventHandlers.volumeChange, false);
      }
      if (eventHandlers.recognizing) {
        plus.speech.removeEventListener('recognizing', eventHandlers.recognizing, false);
      }
      if (eventHandlers.recognition) {
        plus.speech.removeEventListener('recognition', eventHandlers.recognition, false);
      }
      if (eventHandlers.end) {
        plus.speech.removeEventListener('end', eventHandlers.end, false);
      }
      
      // 清空函数引用
      eventHandlers = {};
    } catch (error) {
      console.error('🔧 [监听器] 移除事件监听器失败:', error);
    }
  };

  // 语音识别事件处理
  const onStart = (e: any) => {
    showModal.value = true;
    generateWaveform(0.1);
  };

  const onVolumeChange = (e: any) => {
    generateWaveform(e.volume);
  };

  const onRecognizing = (e: any) => {
    previewText.value = e.partialResult;
  };

  const onRecognition = (e: any) => {
    const now = Date.now();
    const result = e.result;
    
    // 事件去重：检查是否是重复的识别结果
    if (result === lastRecognitionResult && (now - lastRecognitionTime) < 500) {
      return;
    }
    
    recognitionResult.value = result;
    previewText.value = '';
    
    // 更新去重状态
    lastRecognitionResult = result;
    lastRecognitionTime = now;
    
    // 如果正在等待最终结果，停止录音
    if (isWaitingForFinalResult.value) {
      isWaitingForFinalResult.value = false;
      setTimeout(() => {
        if (isRecording.value) {
          stopRecording();
        }
      }, 150);
    }
  };

  const onEnd = (e: any) => {
    const now = Date.now();
    
    // 事件去重：检查是否是重复的结束事件
    if ((now - lastEndTime) < 200) {
      return;
    }
    
    // 更新去重状态
    lastEndTime = now;
    
    // 检查是否需要继续录音（用户还在长按）
    if (isRecording.value && !isWaitingForFinalResult.value) {
      // 继续录音
      setTimeout(() => {
        if (isRecording.value && !isWaitingForFinalResult.value) {
          try {
            plus.speech.startRecognize(speechOptions);
          } catch (error) {
            console.error('继续录音失败:', error);
            isRecording.value = false;
            showModal.value = false;
          }
        }
      }, 100);
    } else {
      // 停止录音
      isRecording.value = false;
      showModal.value = false;
      previewText.value = '';
      generateWaveform(0);
    }
  };

  // 开始录音
  const startRecording = (componentId: string) => {
    
    if (isRecording.value) {
      return false;
    }
    
    isRecording.value = true;
    currentComponentId.value = componentId;
    recognitionResult.value = '';
    previewText.value = '';
    isWaitingForFinalResult.value = false;
    
    // 重置去重状态
    lastRecognitionResult = '';
    lastRecognitionTime = 0;
    lastEndTime = 0;
    
    try {
      plus.speech.startRecognize(speechOptions);
      return true;
    } catch (error) {
      console.error('🎤 [录音] 开始语音识别失败:', error);
      isRecording.value = false;
      currentComponentId.value = null;
      return false;
    }
  };

  // 停止录音
  const stopRecording = () => {
    
    if (!isRecording.value) return;
    
    try {
      plus.speech.stopRecognize();
    } catch (error) {
      console.error('🛑 [录音] 停止语音识别失败:', error);
    }
    
    // 强制重置状态
    isRecording.value = false;
    showModal.value = false;
    previewText.value = '';
    generateWaveform(0);
  };

  // 强制停止录音（用于清理）
  const forceStopRecording = () => {
    
    try {
      plus.speech.stopRecognize();
    } catch (error) {
      console.error('🛑 [录音] 强制停止语音识别失败:', error);
    }
    
    // 强制重置所有状态
    isRecording.value = false;
    showModal.value = false;
    previewText.value = '';
    recognitionResult.value = '';
    currentComponentId.value = null;
    isWaitingForFinalResult.value = false;
    generateWaveform(0);
    
    // 重置去重状态
    lastRecognitionResult = '';
    lastRecognitionTime = 0;
    lastEndTime = 0;
  };

  // 等待最终结果
  const waitForFinalResult = () => {
    isWaitingForFinalResult.value = true;
  };

  // 获取当前录音结果
  const getCurrentResult = () => {
    return recognitionResult.value;
  };

  // 清除结果
  const clearResult = () => {
    recognitionResult.value = '';
    previewText.value = '';
  };

  // 检查是否是当前组件在录音
  const isCurrentComponentRecording = (componentId: string) => {
    return currentComponentId.value === componentId && isRecording.value;
  };

  // 注册组件
  const registerComponent = () => {
    appLevelActiveComponents++;
    
    // 只在第一个组件注册时初始化事件监听器
    if (!appLevelEventListenersInitialized) {
      initEventListeners();
    }
  };

  // 注销组件
  const unregisterComponent = (componentId: string) => {
    appLevelActiveComponents--;
    
    // 如果当前组件正在录音，停止录音
    if (currentComponentId.value === componentId && isRecording.value) {
      forceStopRecording();
    }
    
    // 如果没有活跃组件，清理状态
    if (appLevelActiveComponents <= 0) {
      appLevelActiveComponents = 0;
      appLevelEventListenersInitialized = false;
      forceStopRecording();
    }
  };

  // 初始化事件监听器
  const initEventListeners = () => {
    if (appLevelEventListenersInitialized) {
      return; // 已经初始化过了
    }
    
    try {
      // 先移除可能存在的监听器
      removeAllEventListeners();
      
      // 创建事件处理函数引用
      eventHandlers.start = onStart;
      eventHandlers.volumeChange = onVolumeChange;
      eventHandlers.recognizing = onRecognizing;
      eventHandlers.recognition = onRecognition;
      eventHandlers.end = onEnd;
      
      // 添加事件监听器
      plus.speech.addEventListener('start', eventHandlers.start, false);
      plus.speech.addEventListener('volumeChange', eventHandlers.volumeChange, false);
      plus.speech.addEventListener('recognizing', eventHandlers.recognizing, false);
      plus.speech.addEventListener('recognition', eventHandlers.recognition, false);
      plus.speech.addEventListener('end', eventHandlers.end, false);
      
      appLevelEventListenersInitialized = true;
    } catch (error) {
      console.error('🔧 [监听器] 初始化语音识别事件监听器失败:', error);
    }
  };

  // 清理所有状态（页面卸载时调用）
  const cleanup = () => {
    forceStopRecording();
    appLevelActiveComponents = 0;
    appLevelEventListenersInitialized = false;
    removeAllEventListeners();
  };

  return {
    // 状态
    isRecording,
    currentComponentId,
    recognitionResult,
    previewText,
    waveformData,
    showModal,
    isWaitingForFinalResult,
    
    // 方法
    startRecording,
    stopRecording,
    forceStopRecording,
    waitForFinalResult,
    getCurrentResult,
    clearResult,
    isCurrentComponentRecording,
    registerComponent,
    unregisterComponent,
    initEventListeners,
    cleanup,
    generateWaveform,
    removeAllEventListeners
  };
}); 